﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HtmlAgilityPack;
using inspf.Hup;
using inspf.Use;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace inspf.Default
{
    public class DownLoadFile : ViewModelBase
    {
        public DownLoadFile(string url, string name)
        {
            Url = url;
            Name = name;
        }

        #region private

        public bool IsRuning = false; //是否运行
        private string url; //构造地址
        private int curPage = 1; //起始页
        private int sumPage = 30; //总页数
        public bool Finish = false;
        private ObservableCollection<Goods> goodsList = new ObservableCollection<Goods>();

        private string fontext = "\xea11";//默认启动
        private string name;

        #endregion

        public delegate void dlgMsg();
        public event dlgMsg EventProgressMsg;

        /// <summary>
        /// 字体
        /// </summary>
        public string Fontext
        {
            get { return fontext; }
            set { fontext = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name
        {
            get { return name; }
            set { name = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// URL
        /// </summary>
        public string Url
        {
            get { return url; }
            set { url = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 起始页
        /// </summary>
        public int CurPage
        {
            get { return curPage; }
            set { curPage = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 下载数据集
        /// </summary>
        public ObservableCollection<Goods> GoodsList
        {
            get { return goodsList; }
            set
            {
                goodsList = value; RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 开始任务
        /// </summary>
        public async Task Start()
        {
            await OnClick();
        }

        /// <summary>
        /// 暂停任务
        /// </summary>
        public void Stop()
        {
            if (!IsRuning) return;

            IsRuning = false;
        }

        /// <summary>
        /// 获取任务状态
        /// </summary>
        /// <returns></returns>
        public bool GetTaskStaus()
        {
            return IsRuning;
        }

        /// <summary>
        /// 任务下载
        /// </summary>
        /// <returns></returns>
        private async Task TaskDownAsync()
        {
            while (CurPage < sumPage)//未下载完成
            {
                if (IsRuning) continue;
                try
                {
                    await GetURLContentsAsync(string.Format(Url, CurPage, Guid.NewGuid().ToString()));
                    CurPage++;
                }
                catch
                {
                    IsRuning = false;
                }
            }
            if (CurPage == sumPage)
            {
                Fontext = "\xea11";
                this.Finish = true;
                this.IsRuning = false;
                if (EventProgressMsg != null)
                    EventProgressMsg();
            }
        }

        /// <summary>
        ///  下载数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private async Task GetURLContentsAsync(string url)
        {
            // The downloaded resource ends up in the variable named binder.
            try
            {
                string html = await HttpHelper.DownloadUrl(url);//DownHtml
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);//Loading html
                // 
                HtmlNodeCollection noneNodeList = this.doHtmlSelectNodes(doc, @"//*[@id=""infolist""]/div[{0}]/table/tbody/tr");
                if (noneNodeList == null || noneNodeList.Count == 0)
                {
                    return;
                }
                foreach (var node in noneNodeList)
                {
                    Goods commodity = new Goods();
                    HtmlDocument docChild = new HtmlDocument();
                    docChild.LoadHtml(node.OuterHtml);

                    HtmlNode urlNode = docChild.DocumentNode.SelectSingleNode(@"//*[@class=""t""]/a");
                    if (urlNode != null)
                        commodity.url = urlNode.Attributes["href"].Value;

                    HtmlNode imgNode = docChild.DocumentNode.SelectSingleNode(@"//*[@class=""t""]/a");
                    if (imgNode != null)
                        commodity.brands = imgNode.InnerHtml;

                    HtmlNodeCollection classNode = docChild.DocumentNode.SelectNodes(@"//*[@class=""t""]/span");
                    if (classNode != null)
                    {
                        int i = 0;
                        if (classNode.Count == 5)
                        {
                            i = 1;
                        }
                        commodity.price = Convert.ToDecimal(classNode[i].InnerText.Replace("￥", ""));
                        commodity.productinfo = classNode[i++].InnerText;
                        commodity.area = classNode[i++].InnerText.Split('-')[0].TrimStart().TrimEnd();
                    }

                    HtmlNode qqNode = docChild.DocumentNode.SelectSingleNode(@"//*[@class=""name_add""]");

                    if (qqNode != null)
                        commodity.zzname = qqNode.InnerText;

                    commodity.zzno = Guid.NewGuid().ToString();
                    var isexits = goodsList.Where(q => q.brands != null && q.brands.Equals(commodity.brands)).ToList();
                    if (isexits.Any())
                    {
                        continue;
                    }
                    else
                        goodsList.Add(commodity);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 返回符合XPATH NODES
        /// </summary>
        /// <param name="docment"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        private HtmlNodeCollection doHtmlSelectNodes(HtmlDocument docment, string str, int number = 1)
        {
            HtmlNodeCollection noneNodeList = docment.DocumentNode.SelectNodes(string.Format(str, number));
            if (noneNodeList == null)
            {
                if (number > 6) return noneNodeList;
                number++;
                noneNodeList = doHtmlSelectNodes(docment, str, number);
            }
            return noneNodeList;
        }

        #region 命令

        private RelayCommand _ToClick;

        /// <summary>
        /// 单机命令
        /// </summary>
        public RelayCommand ToClick
        {
            get
            {
                if (_ToClick == null)
                {
                    _ToClick = new RelayCommand(async () => await OnClick());
                }
                return _ToClick;
            }
            set
            {
                _ToClick = value;
            }
        }

        /// <summary>
        /// 执行
        /// </summary>
        public async Task OnClick()
        {
            bool bol = GetTaskStaus();

            if (!bol)
            {
                Fontext = "\xea1a";
                await this.TaskDownAsync();
            }
            else
            {
                Fontext = "\xea11";
                this.Stop();
            }
        }

        #endregion

        /// <summary>
        /// 保存数据
        /// </summary>
        public void SaveChangeds()
        {
            string xlsName = string.Format(BaseConfig.url + BaseConfig.xlsbase, DateTime.Now.ToString("yyyy-MM-dd"), this.Name);

            if (File.Exists(xlsName)) { return; } //一天上传一次, 暂不做增量

            XlsHup.CreateXlsChangeds(xlsName, GoodsList);
        }
    }
}
